/**
 * puppeteer-adapter.js
 *
 * This adapter handles the imports for puppeteer-core package,
 * allowing the application to work with external browsers (like AdsPower).
 * We only use puppeteer-core which does not download Chromium.
 */

// Import only puppeteer-core and related packages to reduce bundle size
let puppeteer;
let StealthPlugin;
let puppeteer_extra;

// Try to import puppeteer-core and related packages
try {
  // Always use puppeteer-core instead of full puppeteer to avoid Chromium download
  puppeteer = await import('puppeteer-core').then(m => m.default);
  StealthPlugin = await import('puppeteer-extra-plugin-stealth').then(m => m.default);
  puppeteer_extra = await import('puppeteer-extra').then(m => m.default);
  console.log('[Puppeteer Adapter] Successfully loaded puppeteer-core packages');
} catch (err) {
  console.error('[Puppeteer Adapter] Failed to load puppeteer-core:', err);

  // Create dummy objects if nothing can be loaded
  // This allows the rest of the code to run and connect to AdsPower browser
  puppeteer = {
    connect: (options) => {
      console.log('[Puppeteer Adapter] Using dummy puppeteer.connect with options:', options);
      // Return minimal browser interface that can connect to external browser
      return Promise.resolve({
        on: (event, callback) => {},
        close: () => Promise.resolve(),
        newPage: () => {
          return Promise.resolve({
            on: (event, callback) => {},
            setViewport: () => Promise.resolve(),
            goto: (url) => Promise.resolve(),
            $: (selector) => Promise.resolve({}),
            $$: (selector) => Promise.resolve([]),
            $eval: (selector, func) => Promise.resolve(),
            evaluate: (func) => Promise.resolve(),
            waitForSelector: () => Promise.resolve({}),
            waitForNavigation: () => Promise.resolve(),
            mouse: {
              move: () => Promise.resolve(),
              down: () => Promise.resolve(),
              up: () => Promise.resolve(),
              click: () => Promise.resolve()
            }
          });
        }
      });
    }
  };

  puppeteer_extra = {
    use: () => {
      return {
        connect: puppeteer.connect
      };
    }
  };

  StealthPlugin = () => {
    return {
      enabledEvasions: {}
    };
  };
}

// Export the puppeteer components
export { puppeteer, StealthPlugin, puppeteer_extra };